package org.ttitfly.ttcore.util.query;

import java.util.ArrayList;
import java.util.List;

import org.displaytag.pagination.PaginatedList;
import org.displaytag.properties.SortOrderEnum;
import org.ttitfly.ttcore.util.WebConstants;

public abstract class PageList<T extends SearchObject> implements PaginatedList {

    /**
     * Number of objects per page.
     */
    protected int objectsPerPage = 15;

    /**
     * Current page (starting from 1)
     */
    protected int pageNumber;

    protected Integer fullListSize = null;

    protected String sort;

    protected String dir;

    protected T so;

    private List<?> objectList = new ArrayList<Object>();

    public PageList(T so) {
        this.so = so;
        /**
         * initialize Sort
         */
        if (so.getSorts().size() > 0) {
            Sort sort = so.getSorts().get(0);
            this.sort = sort.getSortKey();
            this.dir = sort.getSortDir();
        }

    }

    protected abstract int getObjectCount();

    protected abstract List<?> getObjectList();

    public boolean beyondExportLimit() {
        if (so.isExportFull()) {
            return getFullListSize() > so.getExportLimit();
        }
        return false;
    }

    public int getFullListSize() {
        if (fullListSize == null) {
            fullListSize = getObjectCount();
        }
        return fullListSize;
    }

    public List<?> getList() {
        objectList = getObjectList();
        return objectList;
    }

    public int getObjectsPerPage() {
        objectsPerPage = so.getPageSize();
        return objectsPerPage;
    }

    public int getPageNumber() {
        pageNumber = so.getCurrentPage();
        return pageNumber;
    }

    public String getSearchId() {
        return Integer.toHexString(objectsPerPage * 10000 + pageNumber);
    }

    public String getSortCriterion() {
        return sort;
    }

    public SortOrderEnum getSortDirection() {
        if (WebConstants.SORT_ASC.equalsIgnoreCase(dir)) {
            return SortOrderEnum.ASCENDING;
        }

        return SortOrderEnum.DESCENDING;
    }

    public void setObjectsPerPage(int objectsPerPage) {
        this.objectsPerPage = objectsPerPage;
    }

}
